import { Modal, Form, Input, Select } from 'antd'
import api from '@/api'
import { IAction, IModalProp } from '@/types/modal'
import { useImperativeHandle, useState } from 'react'
import { User } from '@/types/api'
import { message } from '@/utils/AntdGlobal'

const CreateUser = (props: IModalProp) => {
  const [form] = Form.useForm()
  const [visible, setVisible] = useState(false)
  const [action, setAction] = useState<IAction>('create')

  const open = (type: IAction, data?: User.userInfo) => {
    setAction(type)
    setVisible(true)
    if (type === 'edit' && data) {
      form.setFieldsValue(data)
    }
  }
  // 暴露子组件的 open 方法
  useImperativeHandle(props.mRef, () => {
    return { open }
  })

  const handleCancel = () => {
    setVisible(false)
    form.resetFields()
  }

  const handleSubmitChanCalls = () => {
    form
      .validateFields()
      .then(res => {
        console.log('表单验证的结果是', res)
      })
      .catch(err => {
        message.error('请查看报错提示，修复后重试！')
        return
      })
  }

  const handleSubmit = async () => {
    let valid = null
    try {
      valid = await form.validateFields()
    } catch (error) {
      message.error('请查看报错提示，修复后重试！')
      return
    }

    console.log('表单验证的结果是：', valid)
    if (!valid) return

    const formValues = form.getFieldsValue()
    const res = await api.saveUser(formValues)
    if (res.success) {
      message.info('保存成功！')
      handleCancel()
      props.update()
    } else {
      console.log('保存用户失败！')
      message.error(res.msg)
    }
  }

  return (
    <Modal
      title='创建用户'
      width={800}
      open={visible}
      onOk={handleSubmit}
      onCancel={handleCancel}
      okText='确定'
      cancelText='取消'
    >
      <Form form={form} labelCol={{ span: 3 }} labelAlign='right'>
        <Form.Item label='id' name='id' hidden={true}>
          <Input />
        </Form.Item>
        <Form.Item label='昵称' name='nickname' rules={[{ required: true, message: '请输入用户名' }]}>
          <Input placeholder='请输入用户昵称'></Input>
        </Form.Item>
        <Form.Item
          label='邮箱'
          name='email'
          rules={[
            { required: true, message: '请输入邮箱' },
            { type: 'email', message: '请输入正确的邮箱' }
          ]}
        >
          <Input placeholder='请输入用户邮箱' disabled={action === 'edit' ? true : false}></Input>
        </Form.Item>
        <Form.Item label='状态' name='state'>
          <Select>
            <Select.Option value={1}>在职</Select.Option>
            <Select.Option value={2}>离职</Select.Option>
            <Select.Option value={3}>试用期</Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default CreateUser
